package com.linjiang.service;

import com.linjiang.spring.BeanPostProcessor;
import com.linjiang.spring.Component;
import com.linjiang.spring.Value;

import java.lang.reflect.Field;
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;

/**
 * 针对value注解的bean的后置处理器实现
 */
@Component
public class ValueBeanPostProcessor implements BeanPostProcessor {

    /**
     * bean初始化前调用该方法
     * @param bean
     * @param beanName
     * @return
     */
    @Override
    public Object postProcessBeforeInitialization(Object bean, String beanName) {
        Class<?> aClass = bean.getClass();
        Field[] fields = aClass.getDeclaredFields();
        for (Field field : fields) {
            //属性上是否存在value注解
            if (field.isAnnotationPresent(Value.class)){
                Value annotation = field.getAnnotation(Value.class);
                String value = annotation.value();
                //根据该注解声明的属性给该bean对象的属性字段赋值
                if ("value".equals(value)){
                    try {
                        field.setAccessible(true);
                        field.set(bean,"xxxxx");
                    } catch (IllegalAccessException e) {
                        throw new RuntimeException(e);
                    }
                }
            }
        }
        return bean;
    }

    /**
     * bean初始化后调用该方法
     * @param bean
     * @param beanName
     * @return
     */
    @Override
    public Object postProcessAfterInitialization(Object bean, String beanName) {
        return bean;
    }
}
